<!--
 * @Description: 巡检计划管理页面
-->

<template>
  <MainSlot v-loading="loading">
    <!-- <template v-slot:searchForm>
      <SearchForm :formItemList="formItemList" @search="search"></SearchForm>
    </template>

<template v-slot:btn>
      <BtnSlot :btnList="btnList" @handleEvent="getBtnEvent"></BtnSlot>
    </template> -->

    <template v-slot:searchForm>
      <SearchForm :formItemList="formItemList" @search="searchData"></SearchForm>
    </template>

    <template v-slot:btn>
      <BtnSlot :btnList="btnList" @handleEvent="getBtnEvent"></BtnSlot>
    </template>

    <template v-slot:table>
      <el-table ref="tableData" v-loading="loading" :data="tableData" stripe border height="calc(100% - 50px)"
        @row-click="handleEdit" @selection-change="handleSelectionChange">
        <!-- @current-change="handleCurrentChange" -->
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column prop="inspectionPlanName" label="巡查计划名称" min-width="120" />
        <!-- <el-table-column prop="inspectionRouteName" label="巡查线路" /> -->
        <el-table-column label="执行频率">
          <template v-if="scope.row.inspectionPlanId" slot-scope="scope">
            <div v-if="
              scope.row.dayRate || scope.row.monthRate || scope.row.hourRate
            ">
              <div v-if="scope.row.dayRate">{{ scope.row.dayRate + "天" }}</div>
              <div v-if="scope.row.hourRate">
                {{ scope.row.hourRate + "时" }}
              </div>
              <div v-if="scope.row.monthRate">
                {{ scope.row.monthRate + "月" }}
              </div>
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="employeeName" label="巡查人" /> -->
        <el-table-column prop="endTime" label="计划状态">
          <template v-if="scope.row.inspectionPlanId" slot-scope="scope">
            <div :style="rowendTime(scope.row.endTime) === '已过期' ? 'color:red' : ''
              ">
              {{ rowendTime(scope.row.endTime) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template v-if="btnFlag_edit || btnFlag_delete" slot-scope="scope">
            <el-button v-show="btnFlag_edit" class="text-btn-cursor" type="primary" plain
              @click="openDialog(scope.row, 'edit')">
              修 改
            </el-button>
            <el-button v-show="btnFlag_delete" class="text-btn-cursor cursor-delete" type="danger" plain
              @click="handleDelete(scope.row)">
              删 除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <template v-slot:pagination>
      <Pagination @size-Change="changePageSize" :size="pageSize" @current-change="changeCurrentPage" :page="currentPage"
        :total="totalSize">
      </Pagination>
    </template>

    <template v-slot:dialogModule>
      <el-dialog :close-on-click-modal="false" :title="dialogTitle + '巡查计划信息'" :visible.sync="dialogFormVisible"
        :before-close="cancel">
        <el-form ref="formData" :model="formData" :rules="rules" class="el-form" label-width="120px">
          <el-form-item label="巡查计划名称:" prop="inspectionPlanName" class="w100p">
            <el-input v-model="formData.inspectionPlanName" placeholder="请输入巡查计划名称" clearable />
          </el-form-item>
          <el-form-item label="计划执行频率:" prop="val" class="w100p">
            <el-row>
              <el-col :span="6">
                <el-form-item prop="rate">
                  <el-select v-model="rate" filterable clearable>
                    <el-option v-for="item in rateList" :key="item.value" :label="item.label"
                      :value="item.value"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="18">
                <el-form-item prop="monthRate" v-if="rate == 'monthRate'">
                  <el-select class="w100p" v-model="formData.monthRate" filterable clearable @change="monthRate">
                    <el-option v-for="(item, index) in 12" :key="index" :value="item" />
                  </el-select>
                </el-form-item>
                <el-form-item prop="dayRate" v-if="rate == 'dayRate'">
                  <el-select class="w100p" v-model="formData.dayRate" filterable clearable @change="dayRate">
                    <el-option v-for="(item, index) in 31" :key="index" :value="item" />
                  </el-select>
                </el-form-item>
                <el-form-item prop="hourRate" v-if="rate == 'hourRate'">
                  <el-select class="w100p" v-model="formData.hourRate" filterable clearable @change="hourRate">
                    <el-option v-for="(item, index) in 24" :key="index" :value="item" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="计划有效时间:" class="w100p">
            <el-row :gutter="10">
              <el-col :span="11">
                <el-form-item prop="startTime" class="w100p">
                  <el-tooltip class="item w100p" effect="dark" content="计划开始时间必须大于当前时间" placement="bottom-end">
                    <el-date-picker class="w100p" v-model="formData.startTime" :picker-options="startDatePicker"
                      type="datetime" placeholder="计划开始日期" value-format="timestamp" />
                  </el-tooltip>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item prop="endTime" class="w100p">
                  <el-date-picker class="w100p" v-model="formData.endTime" :picker-options="endDatePicker"
                    type="datetime" placeholder="计划结束日期" value-format="timestamp" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="计划启停:" prop="inspectionOnOff" class="w100p elRadio">
            <el-switch v-model="inspectionOnOff" />
          </el-form-item>
        </el-form>
        <el-form ref="inspectionRouteId" :model="addformData" :rules="rules" class="el-form" label-width="120px">
          <el-form-item label="任务名称:" prop>
            <el-input v-model="addformData.inspectionTaskName" clearable />
          </el-form-item>
          <el-form-item label="巡查线路:" prop>
            <el-select class="w100p" v-model="addformData.inspectionRouteId" clearable filterable
              @change="changenowPointId">
              <el-option v-for="item in patrolLine" :key="item.inspectionRouteId" :label="item.inspectionRouteName"
                :value="item.inspectionRouteId" />
            </el-select>
          </el-form-item>
          <el-form-item label="巡查人:" prop="address">
            <el-select class="w100p" v-model="addformData.employeeName" clearable filterable>
              <el-option v-for="item in staffData" :key="item.person.personNo" :label="item.person.name"
                :value="item.person.name" />
            </el-select>
          </el-form-item>
          <el-form-item label="任务生成时间:" prop="birthday">
            <el-tooltip class="item" effect="dark" content="任务生成时间必须大于当前时间" placement="bottom">
              <el-date-picker class="w100p" v-model="addformData.generateTime" type="datetime" placeholder="请输入任务生成时间"
                clearable :picker-options="endate" value-format="timestamp" />
            </el-tooltip>
          </el-form-item>
        </el-form>
        <div class="pointList">
          <div class="label-input">
            <div class="label">
              添加任务<i class="el-icon-circle-plus-outline" @click="addPoint()"></i>
            </div>
          </div>
          <div class="tags">
            <div v-for="(items, index) in tagsList" :key="index" class="tag-item" @click="seeTheTag(items)">
              <div class="point-name">{{ items.inspectionTaskName }}</div>
              <div class="close">
                <i class="el-icon-circle-close" @click.stop="removeTheTag(index)"></i>
              </div>
            </div>
          </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')">取 消</el-button>
          <el-button class="zh-button-two" type="primary" @click="save('formData')">保 存</el-button>
        </div>
      </el-dialog>
    </template>
  </MainSlot>
</template>

<script>
import MainSlot from "@/components/MainSlot";
import Pagination from "@/components/Pagination";
import SearchForm from "@/components/SearchForm";
import BtnSlot from "@/components/BtnSlot";
import AddEdit from "./components/addEdit.vue";

import patrolInfoManage from "@/api/patrol-info-manage/patrol-line-manage";
import InspectionPlan from "@/api/patrol-info-manage/patrol-plan-manage";
import staffManage from "@/api/basicInformationOperate/staffManage";
import { mymixin } from "@/utils/mixins";

import { mapGetters } from "vuex";
export default {
  name: "PatrolPlanManage",
  components: {
    SearchForm,
    Pagination,
    MainSlot,
    BtnSlot,
    AddEdit,
  },
  computed: {
    ...mapGetters(["codeList"]),
  },
  mixins: [mymixin],
  data() {
    return {
      btnFlag_edit: false,
      btnFlag_delete: false,
      btnList: ["add", "delete"],
      formConfig: [
        {
          label: "巡查计划名称",
          prop: "inspectionPlanName",
          type: "input",
        },
      ],
      rate: "",
      rateList: [
        { value: "monthRate", label: "月" },
        { value: "dayRate", label: "天" },
        { value: "hourRate", label: "时" },
      ],
      searchFormData: {},
      userName: "",
      // 选中的数据项数组 employeeId组成 (此数组最多为一个)
      selectedStaffList: [],
      patrolLine: [],
      inspectionPlanName: "",
      staffData: [],
      addformData: {},
      formData: {},
      tagsList: [],
      inspectionOnOff: "true",
      startDatePicker: this.beginDate(),
      endDatePicker: this.processDate(),
      endate: this.endates(),
      rules: {
        inspectionPlanName: [
          { required: true, message: "请输入巡查计划名称", trigger: "blur" },
        ],
        val: [
          {
            required: true,
            message: "请选择任意一个执行频率",
            trigger: "blur",
          },
        ],
        startTime: [
          { required: true, message: "请选择开始时间", trigger: "change" },
        ],
        endTime: [
          { required: true, message: "请选择结束时间", trigger: "change" },
        ],
      },
      dialogTitle: "",
      dialogFormVisible: false,
      formItemList: [
        {
          label: "巡查点名称",
          type: "input",
          param: "inspectionPlanName",
          defaultSelect: "",
          isShow: true,
        },
      ],
    };
  },
  watch: {
    formData: {
      handler(val) {
        if (val.monthRate) {
          this.formData.val = val.monthRate;
        }
        if (val.dayRate) {
          this.formData.val = val.dayRate;
        }
        if (val.hourRate) {
          this.formData.val = val.hourRate;
        }
      },
    },
  },
  created() {
    this.getstaffManageList();
    // let that = this;
    // that.getdatatime();
  },
  mounted() {
    this.btnFlag_edit = this.codeList.indexOf("edit") !== -1;
    this.btnFlag_delete = this.codeList.indexOf("delete") !== -1;
    //  查询表格数据
    this.search();
  },
  methods: {
    //  查询表格数据
    getTableDataList() {
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        order: "asc",
        entity: {
          inspectionPlanName:
            this.searchFormData.inspectionPlanName || undefined,
          organizationNo: sessionStorage.organizationNo,
        },
        // supplierId: this.supplierId
      };
      InspectionPlan.getInspectionPlanList(params).then((res) => {
        this.loading = false;
        let data = res.data;
        if (data) {
          this.totalSize = data.totalElements;
          this.tableData = data.content;
          // this.addblankmet();
          this.resetActionBar();
        }
      });
    },
    searchData(data) {
      this.searchFormData = { ...this.searchFormData, ...data };
      this.getTableDataList();
    },
    async getstaffManageList() {
      const { data: res } = await staffManage.getStaffListByCondition();
      this.staffData = res;
      const { data: resp } = await patrolInfoManage.inspectionRouteCondition();
      this.patrolLine = resp;
    },
    rowendTime(e) {
      let endTime = new Date().getTime();
      // let expireTime = (new Date()).getTime() - 1 * 24 * 60 * 60 * 1000
      if (endTime > e) {
        return "已过期";
      } else if (endTime < e) {
        return "未过期";
      }
    },
    // 限制前面日期不能低于后面日期
    beginDate() {
      const self = this;
      return {
        disabledDate(time) {
          if (self.formData.endTime) {
            //  如果结束时间不为空，则小于结束时间
            return new Date(self.formData.endTime).getTime() < time.getTime();
          } else {
            // return time.getTime() > Date.now()// 开始时间不选时，结束时间最大值小于等于当天
          }
        },
      };
    },
    processDate() {
      const self = this;
      // if (self.endTime) {
      return {
        disabledDate(time) {
          if (self.formData.startTime) {
            //  如果开始时间不为空，则结束时间大于开始时间
            self.time = new Date();
            return new Date(self.formData.startTime).getTime() > time.getTime();
          } else {
            // return time.getTime() > Date.now() // 开始时间不选时，结束时间最大值小于等于当天
          }
        },
      };
    },
    endates() {
      const self = this;
      // if (self.endTime) {
      return {
        disabledDate(time) {
          if (self.addformData.generateTime) {
            self.time = new Date();
            return time.getTime() < Date.now() - 1 * 24 * 60 * 60 * 1000;
            // return new Date(self.addformData.generateTime).getTime() < time.getTime();
          } else {
            self.time = new Date();
            return time.getTime() < Date.now() - 1 * 24 * 60 * 60 * 1000;
            // return new Date(self.addformData.generateTime).getTime() < time.getTime();
          }
        },
      };
    },
    changenowPointId(val) {
      this.nowPointId = val;
      this.patrolLine.forEach((item) => {
        if (item.inspectionRouteId === val) {
          this.addformData.inspectionRouteName = item.inspectionRouteName;
        }
      });
    },
    // 新增任务
    addPoint() {
      this.patrolLine.forEach((item) => {
        if (item.inspectionRouteId === this.addformData.inspectionRouteId) {
          this.addformData.inspectionRouteName = item.inspectionRouteName;
        }
      });
      let arr = [];
      arr.push(this.addformData);
      // console.log(this.addformData)
      if (arr.length > 0) {
        if (!this.formData.val) {
          this.$message.warning("请选择计划执行频率！");
          return;
        }
        if (!this.addformData.inspectionRouteId) {
          this.$message.warning("请选择巡查路线！");
          return;
        }
      }
      if (this.tagsList.length > 0) {
        let idList = [];
        idList = this.tagsList.map((item) => item.inspectionTaskName);
        if (idList.includes(arr[0].inspectionTaskName)) {
          this.$message.warning("该任务已经存在~");
          return;
        } else {
          if (!this.addformData.inspectionTaskName) {
            this.$message.warning("任务名称不能为空~");
            return;
          }
          this.tagsList = JSON.parse(JSON.stringify(this.tagsList.concat(arr)));
        }
        this.addformData = {};
      } else {
        if (!this.addformData.inspectionTaskName) {
          this.$message.warning("任务名称不能为空~");
          return;
        }
        this.tagsList = JSON.parse(JSON.stringify(this.tagsList.concat(arr)));
        this.addformData = {};
        return;
      }
    },
    removeTheTag(pointId) {
      this.tagsList.forEach((item, index) => {
        if (index === pointId) {
          this.tagsList.splice(index, 1);
        }
      });
    },
    seeTheTag(e) {
      if (this.addformData.inspectionTaskName !== e.inspectionTaskName) {
        this.addformData = e;
        return;
      }
      if (this.addformData.inspectionTaskName) {
        this.addformData = {};
      } else {
        this.addformData = e;
      }
    },
    monthRate(val) {
      this.formData.val = val;
      if (val) {
        delete this.formData.dayRate;
        delete this.formData.hourRate;
      }
    },
    dayRate(val) {
      this.formData.val = val;
      if (val) {
        delete this.formData.monthRate;
        delete this.formData.hourRate;
      }
    },
    hourRate(val) {
      this.formData.val = val;
      if (val) {
        delete this.formData.monthRate;
        delete this.formData.dayRate;
      }
    },
    search() {
      this.currentPage = 1;
      this.getTableDataList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    //获取选中Btn
    getBtnEvent(flag) {
      console.log(flag);
      if (flag == "add") {
        this.dialogFormVisible = true;
        this.nowChanceStau = "add";
        this.dialogTitle = flag === "add" ? "新增" : "编辑";
      } else if (flag == "delete") {
        if (this.delActive) {
          this.delmessage();
        } else {
          this.$message.warning("请先选择删除项");
        }
      }
    },
    handleEdit(row) {
      // TODO 点击行元素后 edit
      // 点击行清空上一步数据
      this.tagsList = [];
      this.formData = JSON.parse(JSON.stringify(row));
      this.inspectionOnOff = this.formData.inspectionOnOff;
      // console.log(this.inspectionOnOff)
      delete this.formData.deleteFlagName;
      // console.log(this.formData)
      if (row.inspectionPlanId) {
        InspectionPlan.queryInspectionPlan(row.inspectionPlanId).then((res) => {
          // console.log(res)
          let data = res.data;
          this.tagsList = data.inspectionTaskList;
        });
      }
      // this.tagsList = this.formData.inspectionTaskList
      // this.addActive = false;
      this.editActive = true;
      this.saveActive = false;
      this.cancelActive = true;
    },
    handleSelectionChange(list) {
      this.inspectionPlanIdList = [];
      this.inspectionPlanIdList = list.map((item) => item.inspectionPlanId);
      if (this.inspectionPlanIdList.length > 0) this.delActive = true;
      else this.delActive = false;
    },
    delmessage() {
      InspectionPlan.delInspectionPlaniInfo(this.inspectionPlanIdList).then(
        (res) => {
          if (res.code === 1) {
            this.$message.success(res.msg);
            this.$refs.formData.resetFields();
            this.search();
            this.resetActionBar();
          } else {
            this.$message.warning(res.msg || "删除失败");
          }
        }
      );
    },
    handleDelete(data) {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass",
      })
        .then(() => {
          InspectionPlan.delInspectionPlaniInfo([data.inspectionPlanId]).then(
            (res) => {
              if (res.code === 1) {
                this.$message.success(res.msg);
                this.search();
                this.resetActionBar();
              } else {
                this.$message.warning(res.msg || "删除失败");
              }
            }
          );
        })
        .catch(() => {
          this.$message("取消删除");
        });
    },
    cancel(formData) {
      this.deleteFlag = true;
      this.nowChanceStau = "";
      this.formData = {};
      this.tagsList = [];
      this.rate = '',
        this.addformData = {};
      this.inspectionOnOff = false;
      this.addActive = true;
      this.delActive = false;
      this.saveActive = false;
      this.cancelActive = false;
      this.editActive = false;
      this.closeDialog();
      if (formData) {
        this.$refs['formData'].resetFields();
      }
      this.$refs.tableData.setCurrentRow();
    },
    save(formData) {
      // console.log(this.formData)
      this.$refs[formData].validate((valid) => {
        if (valid) {
          if (this.nowChanceStau === "edit") {
            this.formData.inspectionTaskList = this.tagsList;
            this.formData.inspectionOnOff = this.inspectionOnOff;
            delete this.formData.val;
            InspectionPlan.editInspectionPlaniInfo(this.formData).then(
              (res) => {
                if (res.code === 1) {
                  this.$message.success(res.msg || "修改成功！");
                  this.closeDialog();
                  this.$refs[formData].resetFields();
                  this.search();
                } else {
                  this.$message.error(res.msg || "修改失败！");
                }
              }
            );
          } else if (this.nowChanceStau === "add") {
            this.formData.inspectionOnOff = this.inspectionOnOff;

            this.formData.inspectionTaskList = this.tagsList;
            // if(this.formData.inspectionTaskList) {
            //   this.$message.warning('新建计划，任务')
            // }
            // console.log(this.formData)
            // return
            delete this.formData.val;
            InspectionPlan.addInspectionPlaniInfo(this.formData).then((res) => {
              if (res.code === 1) {
                this.$message.success(res.msg || "新增成功！");
                this.closeDialog();
                this.$refs[formData].resetFields();
                this.search();
              } else {
                this.$message.error(res.msg || "新增失败！");
              }
            });
          }
        } else {
          // console.log('error submit!!');
          return false;
        }
      });
    },
    openDialog(val, type) {
      this.formData = JSON.parse(JSON.stringify(val));
      this.rate = val.monthRate
        ? "monthRate"
        : val.dayRate
          ? "dayRate"
          : val.hourRate
            ? "hourRate"
            : "";
      this.dialogTitle = type === "add" ? "新增" : "编辑";
      this.nowChanceStau = type;
      this.dialogFormVisible = true;
      console.log(val, type, this.formData, "每一行的数据");
    },
    closeDialog() {
      this.dialogFormVisible = false;
      this.dialogTitle = null;
      this.nowChanceStau = "";
    },
  },
};
</script>

<style lang="scss" scoped>
.pointList {
  .label-input {
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    align-items: center;

    .label {
      min-width: 80px !important;
      text-align: end;
      height: 30px;
      font-size: 10px;
      line-height: 30px;
      padding-right: 5px;
    }
  }

  i {
    font-size: 30px;
    margin-left: 10px;
    cursor: pointer;
  }

  .noClick {
    cursor: not-allowed;
  }

  .df {
    display: flex;
    align-items: center;
    width: 100%;
  }

  ::v-deep .el-form-item__content {
    flex-direction: column;
  }

  .label {
    min-width: 100px !important;
  }

  .tags {
    width: 100%;
    display: flex;
    flex-wrap: wrap;

    .tag-item {
      height: 30px;
      padding: 5px 10px;
      background-color: #27dbff;
      border-radius: 8px;
      display: flex;
      align-items: center;
      margin-top: 10px;
      margin-right: 10px;

      i {
        font-size: 14px;
      }
    }
  }
}
</style>
